package com.zm.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;


/**
 * 与当前线程的连接进行绑定
 */
public class ConnectionUtil {

    //实例绑定线程对象
    private ThreadLocal<Connection> tl=new ThreadLocal<Connection>();

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Connection getThreadConnection(){
     //先从当前的线程中获取连接
        Connection conn=tl.get();
            try {
                //判断当前线程针对某一个服务是否有连接
                if(conn==null){
                conn=dataSource.getConnection();
                //将连接与当前线程进行绑定，设置当前线程共享的变量为数据源
                tl.set(conn);
                return conn;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return conn;
    }

    /**
    * 将当前的线程的连接解绑
    */
    public void removeConn(){
        //将tl.set(conn);
        tl.remove();
    }
}
